import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { routerRedux } from 'dva/router';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Card,
  Icon,
  Tooltip,
  List,
  Avatar,
  Button,
  Switch,
  Input,
  Form,
  Drawer,
  message,
  Spin,
  Modal
} from 'antd';
import del1Img from '@/assets/knowledge/del1.png';
import editImg from '@/assets/knowledge/edit.png';
import addImg from '@/assets/dialog/add.png';
import onImg from '@/assets/knowledge/on.png';
import offImg from '@/assets/knowledge/off.png';
import styles from './index.less';
import jqr from '@/assets/OverviewRobots/jqr.png';
import deleteimg from '@/assets/OverviewRobots/delete.png';
const FormItem = Form.Item;
const Search = Input.Search;
class HomeOver extends Component {
  state = {
    login: false,
    valueMax: true,
    pdx: null,
    pdxTwo: null,
    list: [null],
    teamList: [],
    total: '',
    namejqr: '',
    cssblock: '-1',
  };

  componentDidMount() {
    const { dispatch, currentUser } = this.props;
    this.robotGetRobotList();
  }

  // 获取数据
  robotGetRobotList = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const uid =
      window.localStorage.getItem('uid') == undefined ? '' : window.localStorage.getItem('uid');
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'home/robotGetRobotList',
        payload: { userId: uid },
        callback: res => {
          console.log('列表数据', res);
          if (!res.code) {
            if (res.data.ownRobot) {
              this.setState(
                {
                  list: [null, ...res.data.ownRobot],
                  login: false,
                },
                () => {
                  let a = [...res.data.ownRobot];
                  let b = [null, ...res.data.ownRobot];
                  a.map((item, index) => {
                    const robotIds =
                      window.localStorage.getItem('robotId') == undefined
                        ? ''
                        : window.localStorage.getItem('robotId');
                    if (item.id === robotIds) {
                      b[index + 1].robotIdkey = '1';
                      this.setState({ list: b });
                    }
                  });
                }
              );
            }
            if (res.data.coopertion) {
              res.data.coopertion.map((item, index) => {
                const robotIds =
                  window.localStorage.getItem('robotId') == undefined
                    ? ''
                    : window.localStorage.getItem('robotId');
                if (item.id === robotIds) {
                  res.data.coopertion[index].robotIdkey = '1';
                }
                this.setState({
                  teamList: res.data.coopertion,
                  login: false,
                });
              });
            }
          }
        },
      });
    });
  };

  // 通过名称搜索机器人
  getRobotByName = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const { dictNames } = this.state;
    if (dictNames) {
      const uid =
        window.localStorage.getItem('uid') == undefined ? '' : window.localStorage.getItem('uid');
      console.log(currentUser, uid);
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'home/getRobotByName',
          payload: { createUserId: uid, robotName: dictNames },
          callback: res => {
            console.log('列表数据', res);
            if (!res.code) {
              if (res.data.ownRobot.length) {
                console.log('创建机器人');
                this.setState(
                  {
                    list: [null, ...res.data.ownRobot],
                    login: false,
                  },
                  () => {
                    let a = [...res.data.ownRobot];
                    let b = [null, ...res.data.ownRobot];
                    a.map((item, index) => {
                      const robotIds =
                        window.localStorage.getItem('robotId') == undefined
                          ? ''
                          : window.localStorage.getItem('robotId');
                      if (item.id === robotIds) {
                        b[index + 1].robotIdkey = '1';
                        this.setState({ list: b });
                      }
                    });
                  }
                );
              }
              if (res.data.coopertion.length) {
                console.log('协作机器人');
                res.data.coopertion.map((item, index) => {
                  const robotIds =
                    window.localStorage.getItem('robotId') == undefined
                      ? ''
                      : window.localStorage.getItem('robotId');
                  if (item.id === robotIds) {
                    res.data.coopertion[index].robotIdkey = '1';
                  }
                  this.setState({
                    teamList: res.data.coopertion,
                    login: false,
                  });
                });
              }
            }
          },
        });
      });
    } else {
      this.robotGetRobotList();
    }
  };

  rktbonChange = (e, index, a) => {
    this.setState({ login: true });
    a.stopPropagation();
    console.log(e, index);
    const { list } = this.state;
    list[index].disabled = !e;
    this.setState({ list, namejqr: list[index] }, () => {
      console.log(this.state.list);
    });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'home/updateRobot',
        payload: {
          userId: currentUser.uid,
          robotId: list[index].id,
          disabled: !list[index].disabled,
        },
        callback: res => {
          console.log('权限', res);
          if (!res.code) {
            message.success(`${res.msg}`);
            this.robotGetRobotList();
          }
          this.setState({ login: false });
        },
      });
    });
  };

  teamonChange = (e, index) => {
    console.log(e, index);
    const { teamList } = this.state;
  };

  showRev = (a, b) => {
    // console.log(a, b);
    this.setState({ pdx: b });
  };

  showRevS = (a, b) => {
    this.setState({ pdx: null });
  };

  showRevTwo = (a, b) => {
    // console.log(a, b);
    this.setState({ pdxTwo: b });
  };

  showRevSTwo = (a, b) => {
    this.setState({ pdxTwo: null });
  };

  // 新建机器人
  newRobot = () => {
    console.log('22');
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: '/overviewRobots/NewRobot',
        params: {},
      })
    );
  };

  // 删除机器人
  deletionRobot = (item, index, e) => {
    //  console.log(e)
    e.stopPropagation(); // 阻止冒泡
    Modal['confirm']({
      title: '删除机器人',
      content: '是否确定删除此机器人？',
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        const { dispatch, currentUser } = this.props;
        if (currentUser.robotId === item.id) {
          console.log('正在使用的机器人无法删除');
          message.error(`该机器人正在使用,无法删除`);
        } else {
          console.log('没有正在使用的机器人可以删除');
          console.log(item, index);
          this.setState({ login: true });

          const robotvo = {
            userId: item.guest,
            robotId: item.id,
          };
          this.reqRef = requestAnimationFrame(() => {
            dispatch({
              type: 'home/robotDelRobot',
              payload: robotvo,
              callback: res => {
                console.log('删除机器人', res);
                if (!res.code) {
                  message.success('删除成功');
                  window.location.reload();
                  this.robotGetRobotList();
                } else {
                  this.setState({ login: false });
                }
              },
            });
          });
        }
      },
      onCancel() {
        console.log('onCancel');
      },
    });
  };

  editUser = (item, index) => {
    const { list } = this.state;
    let a = list.slice(1);
    a.map(items => {
      items.robotIdkey = '2';
    });
    list[index].robotIdkey = '1';
    this.setState({ list: [null, ...a], login: true });
    const { dispatch, currentUser } = this.props;
    console.log(item);
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'home/sysUpdateUser',
        payload: { robotName: item.name, robotId: item.id, uid: item.guest, active: true },
        callback: res => {
          console.log('选中状态', res);
          if (!res.code) {
            message.success(`${res.msg}`);
            window.localStorage.setItem('robotId', item.id);
            window.location.reload();
            // window.location.replace("http://www.runoob.com")
            // this.setState({login:false})
          }
          this.setState({ login: false });
        },
      });
    });
  };

  editUsertwo = (item, index) => {
    const uid =
      window.localStorage.getItem('uid') == undefined ? '' : window.localStorage.getItem('uid');
    const { teamList } = this.state;
    console.log(teamList);
    teamList.map(items => {
      items.robotIdkey = '2';
    });
    teamList[index].robotIdkey = '1';
    this.setState({ teamList, login: true });
    const { dispatch, currentUser } = this.props;
    console.log(item);
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'home/sysUpdateUser',
        payload: { robotName: item.name, robotId: item.id, uid, active: true },
        callback: res => {
          console.log('选中状态', res);
          if (!res.code) {
            window.localStorage.setItem('robotId', item.id);
            message.success(`${res.msg}`);
            // this.abc(item,index)
            window.location.reload();
            // this.setState({login:false})
          }
          this.setState({ login: false });
        },
      });
    });
  };

  // abc = (item,index)=> {
  //   const { dispatch, currentUser } = this.props;
  //   const uid = (window.localStorage.getItem("uid")) == undefined ? '' : (window.localStorage.getItem("uid")) ;
  //   this.reqRef = requestAnimationFrame(() => {
  //     dispatch({
  //       type: 'home/getcoopRotbotMenus',
  //       payload:{ robotId:item.id,userId:uid},
  //       callback: res => {
  //         console.log('选中状态', res);
  //         window.localStorage.setItem("Menus", res.data);
  //         window.location.reload()

  //       },
  //     });
  //   });
  // }

  render() {
    const { list, teamList, cssblock } = this.state;
    // console.log(list)
    return (
      <div className={styles.dabj}>
        <Spin spinning={this.state.login}>
          <p style={{ marginLeft: 20, marginTop: 10 }} className="titleA">
            机器人总览
          </p>
          <div style={{ height: 50 }} />
          <span style={{ marginLeft: 20, marginTop: 10 }} className="titleA">
            我的创建
          </span>
          <span
            style={{ float: 'right', marginRight: 23, position: 'relative', bottom: 15 }}
            className="zdyinputa"
          >
            <Search
              placeholder="请输入机器人名称"
              onSearch={value => {
                console.log(value);
                this.setState({ dictNames: value, page: 1, teamList: [], list: [] }, () => {
                  this.getRobotByName();
                });
              }}
              style={{ height: 50, width: 312 }}
            />
          </span>
          <div style={{ height: 15 }} />
          <div style={{ margin: 20, display: 'inline-block' }}>
            {list.map((items, index) =>
              items ? (
                <div
                  onClick={() => this.editUser(items, index)}
                  style={items.robotIdkey === '1' ? { filter: 'brightness(100%)' } : {}}
                  // style={cssblock===index?{filter:'brightness(100%)'}:{}}
                  className={styles.block}
                  onMouseOver={() => {
                    this.showRev(items, index);
                  }}
                  onMouseOut={() => {
                    this.showRevS(items, index);
                  }}
                  key={index}
                >
                  {this.state.pdx === index ? (
                    <img
                      onClick={e => {
                        this.deletionRobot(items, index, e);
                      }}
                      style={{ float: 'right', position: 'absolute', right: '-1px' }}
                      src={deleteimg}
                    />
                  ) : (
                    <img
                      style={{
                        float: 'right',
                        position: 'absolute',
                        right: '-1px',
                        display: 'none',
                      }}
                      src={deleteimg}
                    />
                  )}

                  <img style={{ marginTop: 30 }} src={jqr} />
                  <p
                    style={{
                      textAlign: 'center',
                      fontSize: 21,
                      color: '#4a90e2',
                      marginTop: 10,
                      marginBottom: 10,
                    }}
                  >
                    {items.name}
                  </p>
                  <div className="zdyswer">
                    <Switch
                      defaultChecked
                      onChange={(event, e) => {
                        this.rktbonChange(event, index, e);
                      }}
                      checked={items.disabled}
                    />
                  </div>
                </div>
              ) : (
                <div onClick={this.newRobot} className={styles.blocks}>
                  <span style={{ fontSize: 21 }}>
                    <Icon style={{ color: '#4a90e2', fontSize: 18 }} type="plus" /> 新建机器人
                  </span>
                </div>
              )
            )}
          </div>
          <p style={{ marginLeft: 20, marginTop: 10 }} className="titleA">
            协作开发
          </p>
          <div style={{ margin: 20, display: 'inline-block' }}>
            {teamList.map((items, index) =>
              items ? (
                <div
                  onClick={() => this.editUsertwo(items, index)}
                  style={items.robotIdkey === '1' ? { filter: 'brightness(100%)' } : {}}
                  onMouseOver={() => {
                    this.showRevTwo(items, index);
                  }}
                  onMouseOut={() => {
                    this.showRevSTwo(items, index);
                  }}
                  className={styles.block}
                  key={index}
                >
                  {/* {this.state.pdxTwo === index ? (
                    <img
                      onClick={e => {
                        this.deletionRobot(items, index, e);
                      }}
                      style={{ float: 'right', position: 'absolute', right: '-1px' }}
                      src={deleteimg}
                    />
                  ) : (
                    <img
                      style={{
                        float: 'right',
                        position: 'absolute',
                        right: '-1px',
                        display: 'none',
                      }}
                      src={deleteimg}
                    />
                  )} */}
                  <img style={{ marginTop: 30 }} src={jqr} />
                  <p
                    style={{
                      textAlign: 'center',
                      fontSize: 21,
                      color: '#4a90e2',
                      marginTop: 10,
                      marginBottom: 10,
                    }}
                  >
                    {items.name}
                  </p>
                </div>
              ) : (
                <div className={styles.blocks}>
                  <span style={{ fontSize: 21 }}>
                    <Icon style={{ color: '#4a90e2', fontSize: 18 }} type="plus" /> 新建多轮会话
                  </span>
                </div>
              )
            )}
          </div>
        </Spin>
      </div>
    );
  }
}

// export default HomeOver;
export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(HomeOver));
